package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hmall.common.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.impl.OrderDetailService;
import com.hmall.order.service.impl.OrderLogisticsService;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.similarities.Lambda;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: cuiliangbo
 * @Date: 2022/6/16 22:10
 */
@SuppressWarnings("all")
@Slf4j
@Component
public class OrderListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private ItemClient itemClient;

    /**
     * 接受过期信息
     * @param orderId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.ttl.queue",declare = "true"),
            exchange = @Exchange(name = "dl.ttl.exchange"),
            key = "dl"
    ))
    public void listenDlQueue(String orderId){

        log.info("接收到 dl.ttl.queue的延迟消息：{}", orderId);
        //调用清理订单的方法，检查orderid对应的status是否已支付，如果没有改状态恢复库存
        //清理订单自己实现

        Order order = orderService.getById(orderId);
        Integer status = order.getStatus();
        if (status == 1){
            //删除订单
            orderService.removeById(orderId);

            //删除订单相信信息
            LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            orderDetailService.remove(orderDetailQueryWrapper);

            //删除订单对应地址信息
            LambdaQueryWrapper<OrderLogistics> logisticsQueryWrapperQueryWrapper = new LambdaQueryWrapper<>();
            orderLogisticsService.remove(logisticsQueryWrapperQueryWrapper);

            //修改库存
            OrderDetail orderDetail = orderDetailService.getOne(orderDetailQueryWrapper);
            itemClient.restoreStock(orderDetail.getItemId(),orderDetail.getNum());

        }


    }

}
